<template>
  <div>
    <!-- 新增 -->
    <a-modal :width="600" :visible="visible" :confirm-loading="loading" :forceRender="true" :maskClosable="false"
      :title="isUpdate ? '编辑标签' : '添加标签'" :body-style="{ paddingBottom: '8px' }" @update:visible="updateVisible"
      @ok="save" @close="updateVisible(false)">
      <a-form ref="formRef" :model="form" :rules="rules" :label-col="{ md: { span: 5 }, sm: { span: 24 } }"
        :wrapper-col="{ md: { span: 17 }, sm: { span: 24 } }">
        <a-form-item label="标签名称:" name="name">
          <a-input v-model:value="form.name" placeholder="标签名称(不可重复)" allow-clear @input="handleInput"
            autocomplete="off" :maxlength="32" />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script lang="ts" setup>
import { computed, ref, reactive, watch, nextTick } from 'vue';
import { message } from 'ant-design-vue/es';
import type { FormInstance } from 'ant-design-vue/es/form';
import useFormData from '/@/utils/common/use-form-data';
import { useUserStore } from '/@/store/modules/user';
import { TagStyleInfoApi } from '/@/api/touch/tagStyle/TagStyleInfoApi';
import { StyleInfoApi } from '/@/api/touch/styleInfo/StyleInfoApi';
import { TagStyleInfoRequest } from '/@/api/touch/tagStyle/model/TagStyleInfoModel';
import { FileApi, FileUploadUrl } from '/@/api/system/operation/FileApi';
import Unauthorized from 'ant-design-vue/lib/result/unauthorized';

const emit = defineEmits<{
  (e: 'done'): void;
  (e: 'update:visible', value: boolean): void;
}>();

const props = defineProps<{
  // 弹窗是否打开
  visible: boolean;
  // 是否是修改
  isUpdate: false;
  // 修改回显的数据
  data?: Object;
  // 组织机构列表
  orgList: Array<{ id: string; name: string; children?: Array<any> }>;
}>();
// 组织列表
const orgLists = ref(props.orgList);

// 强制刷新组件的 key
const treeSelectKey = ref(0);
// 表单实例
const formRef = ref<FormInstance | null>(null);
// 提交状态
const loading = ref<boolean>(false);
// newFlag check
const newFlagChecked = ref<boolean>(false);
const hotFlagChecked = ref<boolean>(false);
const fileList = ref([]);

// 表单数据
let { form, resetFormFields } = useFormData<TagStyleInfoRequest>({
  name: undefined,
});

// 表单验证规则
const rules = reactive({
  name: [{ required: true, message: '请输入标签名称', type: 'string', trigger: 'change' }],
});

watch(
  () => props.visible,
  () => {
    console.log('props.visible', props.visible);
    if (!props.visible) {
      resetFormFields();
      formRef.value?.clearValidate();
      fileList.value = [];
    } else {
      if (Object.keys(props.data || {}).length === 0) {
        resetFormFields();
        formRef.value?.clearValidate();
        fileList.value = [];
      } else {
        form = Object.assign({}, props.data);
      }
    }
  },
);

/**
 * 保存编辑
 *
 */  let flag = false

const save = async () => {

  await StyleInfoApi.validName(form).then((result) => {
    console.log(result, 'result');
    // {"success":false,"code":"A10001","message":"查询结果不存在","data":null,"exceptionClazz":"ServiceException","exceptionTip":"查询结果不存在","exceptionPlace":"cn.stylefeng.guns.modular.service.impl.StyleInfoServiceImpl.queryStyleInfo(StyleInfoServiceImpl.java:131)"}
    result.length === 0 ? flag = false : flag = true
  });

  if (flag) {
    return message.warn('标签名称不可重复')
  }
  // 校验表单
  if (!formRef.value) {
    return;
  }
  formRef.value.validate().then((valid) => {
    console.log('valid', valid);
    if (valid) {



      // if (newFlagChecked.value === true) {
      //   form.newFlag = 'Y';
      // } else {
      //   form.newFlag = 'N';
      // }
      // if (hotFlagChecked.value === true) {
      //   form.hotFlag = 'Y';
      // } else {
      //   form.hotFlag = 'N';
      // }

      // // 获取已上传图片的fileId
      // form.imageFileId = imageFileId.value;
      // 修改加载框为正在加载
      loading.value = true;
      // 执行新增保存
      if (props.isUpdate) {
        StyleInfoApi.edit(form).then((result) => {
          // 移除加载框
          loading.value = false;
          // 提示添加成功
          message.success(result.message);
          // 关闭弹框，通过控制visible的值，传递给父组件
          updateVisible(false);
          // 触发父组件done事件
          emit('done');
          // 重置表单字段
          resetFormFields();
          formRef.value?.clearValidate();
          formRef.value?.resetFields();
          // form = {};

          // form = {
          //   imageFileId: undefined,
          //   style: undefined,
          //   newFlag: undefined,
          //   hotFlag: undefined,
          // };
          // 重置表单数据和状态
        });
      } else {
        StyleInfoApi.add(form)
          .then((result) => {
            console.log(result, 'dsaa');
            // 移除加载框
            loading.value = false;
            // 提示添加成功
            message.success(result.message);
            // 关闭弹框，通过控制visible的值，传递给父组件
            updateVisible(false);
            // 触发父组件done事件
            emit('done');
            // 重置表单字段
            resetFormFields();
            formRef.value?.clearValidate();
            formRef.value?.resetFields();
            // 重置表单数据和状态
          })
          .catch(() => {
            loading.value = false;
          });
      }
    }
  });
};

/**
 * 更新编辑菜单界面的弹框是否显示
 *
 * @param value true-显示，false-隐藏
 * @author jiawei
 * @date 2021/4/7 12:00
 */

const updateVisible = (value: boolean) => {
  emit('update:visible', value);
  resetFormFields();
  formRef.value?.clearValidate();

  Object.keys(form).forEach((key) => {
    form[key] = undefined;
  });
};
const handleInput = (event) => {
  console.log('event', event);
  const maxLength = 32;
  if (event.target.value.length > maxLength) {
    form.style = event.target.value = event.target.value.slice(0, maxLength);
  }
};
</script>